package com.coder4j.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.coder4j.entity.SDisplayInterfaceDetailEntity;
import com.coder4j.entity.STaskFlowDetailEntity;
import com.coder4j.entity.dto.moudle_1;
import com.coder4j.entity.dto.moudle_2;
import com.coder4j.entity.dto.moudle_3;
import com.coder4j.mapper.STaskFlowDetailMapper;
import com.coder4j.starter.web.BaseServiceImpl;
import com.coder4j.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class STaskFlowDetailService extends BaseServiceImpl<STaskFlowDetailMapper, STaskFlowDetailEntity, STaskFlowDetailVO> {

    @Resource
    private STaskFlowDetailMapper mapper;

    @Resource
    private SDisplayInterfaceDetailService sDisplayInterfaceDetailService;

    @Resource
    private SControlDetailService sControlDetailService;


    @Resource
    private SDisplayInterfaceService sDisplayInterfaceService;


    @Override
    public STaskFlowDetailVO entity2Vo(STaskFlowDetailEntity entity) {
        STaskFlowDetailVO vo = new STaskFlowDetailVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    @Override
    public STaskFlowDetailEntity vo2Entity(STaskFlowDetailVO vo) {
        STaskFlowDetailEntity entity = new STaskFlowDetailEntity();
        BeanUtils.copyProperties(vo, entity);
        return entity;
    }

    public List<Map<String, Object>> getTaskLabelList(Integer taskFlowId) {
        return mapper.selectListForAllLabelByTaskFlowId(taskFlowId);
    }


    public Object taskNet(Integer id, Integer type, Integer disPlayId, Integer controlId) {
        //根据任务ID 找到 对应的界面ID
        List<STaskFlowDetailEntity> list = mapper.getByTaskFlowId(id);
        Map<Integer, String> displayArea = null;
        Map<Integer, String> control = null;
        if (type == 1) {
            displayArea = getDisplayArea(disPlayId);
        }
        if (type == 2) {
            displayArea = getDisplayArea(disPlayId);
            control = getControl(controlId);
        }


        List<TreeNode> nodeList = CollUtil.newArrayList();
        for (STaskFlowDetailEntity sTaskFlowDetailEntity : list) {
            TreeNode<String> stringTreeNode = new TreeNode<String>();
            stringTreeNode.setId(String.valueOf(sTaskFlowDetailEntity.getId()));

            stringTreeNode.setName(sTaskFlowDetailEntity.getNodeName());
            Map<String, Object> extra = new HashMap<>();
            extra.put("label", sTaskFlowDetailEntity.getNodeName());
            extra.put("type", sTaskFlowDetailEntity.getNodeName());
            extra.put("width", 100);
            extra.put("height", 40);
            extra.put("flowId", sTaskFlowDetailEntity.getId());
            if (type == 1) {
                if (displayArea.containsKey(sTaskFlowDetailEntity.getId())) {
                    JSONObject entries = new JSONObject();
                    //entries.putOnce("label", JSONUtil.parseObj(displayArea.get(sTaskFlowDetailEntity.getId())).getStr("name"));
                    entries.putOnce("label", displayArea.get(sTaskFlowDetailEntity.getId()));
                    entries.putOnce("width", 100);
                    entries.putOnce("height", 40);
                    extra.put("category", entries);
                }
            }
            if (type == 2) {
                if (control.containsKey(sTaskFlowDetailEntity.getId())) {
                    JSONObject entries = new JSONObject();
                    //entries.putOnce("label",JSONUtil.parseObj(displayArea.get(sTaskFlowDetailEntity.getId())).getStr("name"));
                    entries.putOnce("control", control.get(sTaskFlowDetailEntity.getId()));
                    entries.putOnce("width", 100);
                    entries.putOnce("height", 40);
                    extra.put("category", entries);
                }
            }

            String fId = sTaskFlowDetailEntity.getFId().replaceAll("\\[", "").replaceAll("]", "");
            System.out.println(fId);
            if (fId.contains(",")) {
                // 使用 Hutool 将字符串解析为 JSONArray
                JSONArray jsonArray = JSONUtil.parseArray(sTaskFlowDetailEntity.getFId());
                // 将 JSONArray 转换为 String[]
                String[] stringArray = jsonArray.toArray(new String[0]);
                extra.put("pointTo", stringArray);
                extra.put("pId", fId.split(",")[0]);
                stringTreeNode.setParentId(fId.split(",")[0]);
            } else {
                stringTreeNode.setParentId(sTaskFlowDetailEntity.getFId().replaceAll("\\[", "").replaceAll("]", ""));
            }
            stringTreeNode.setExtra(extra);
            nodeList.add(stringTreeNode);
        }


        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都有默认值的
        treeNodeConfig.setWeightKey("order");
        treeNodeConfig.setIdKey("id");
        // 最大递归深度
        treeNodeConfig.setDeep(10);

        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<TreeNode, String>build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getId()));
                    tree.setParentId(String.valueOf(treeNode.getParentId()));
                    // 扩展属性 ...
                    tree.putExtra("label", treeNode.getExtra().get("label"));
                    tree.putExtra("width", treeNode.getExtra().get("width"));
                    tree.putExtra("height", treeNode.getExtra().get("height"));
                    tree.putExtra("flowId", treeNode.getExtra().get("flowId"));
                    tree.putExtra("flowId", treeNode.getExtra().get("flowId"));
                    tree.putExtra("pointTo", treeNode.getExtra().get("pointTo"));
                    tree.putExtra("category", treeNode.getExtra().get("category"));
                });



        return treeNodes;
    }

    private Map<Integer, String> getDisplayArea(Integer disPlayId) {
        /*List<Integer> ids = new ArrayList<>();
        for (STaskFlowDetailEntity sTaskFlowDetailEntity : list) {
            ids.add(sTaskFlowDetailEntity.getId());
        }
        List<SDisplayInterfaceDetailVO> displayInterfaceDetailVOS = mapper.getListByTaskDetailIds(ids);
        //isplay_interface_id 不等于 disPlayId 的数据
        List<SDisplayInterfaceDetailVO> filteredDisplayInterfaceDetailVOS = displayInterfaceDetailVOS.stream()
                .filter(vo -> vo.getDisplayInterfaceId().equals(disPlayId))
                .collect(Collectors.toList());

        Map<Integer, String> collect = filteredDisplayInterfaceDetailVOS.stream().collect(Collectors.toMap(SDisplayInterfaceDetailVO::getTaskFlowDetailId, SDisplayInterfaceDetailVO::getInterestArea));
*/
        Map<Integer, String> collect = new HashMap<>();
        SDisplayInterfaceDetailQuery sDisplayInterfaceDetailQuery = new SDisplayInterfaceDetailQuery();
        sDisplayInterfaceDetailQuery.setDisplayInterfaceId(disPlayId);
        Map<String,JSONArray> idToArea = new HashMap<>();
        List<Integer> taskDetailsIds = new ArrayList<>();
        List<SDisplayInterfaceDetailEntity> sDisplayInterfaceDetailEntities = sDisplayInterfaceDetailService.baseQueryList(sDisplayInterfaceDetailQuery);
        for (SDisplayInterfaceDetailEntity sDisplayInterfaceDetailEntity : sDisplayInterfaceDetailEntities) {
            String interestArea = sDisplayInterfaceDetailEntity.getInterestArea();
            //{"color":"#5DC2F3","x":256.9375,"width":121,"name":"区域 1","y":116,"taskId":[1,2],"height":81}
            JSONObject entries = JSONUtil.parseObj(interestArea);
            String name = entries.getStr("name");
            JSONArray taskId = entries.getJSONArray("taskId");
            for (Object o : taskId) {
                taskDetailsIds.add(Integer.parseInt(o.toString()));
            }
            idToArea.put(name,taskId);
        }

        for (Integer taskDetailsId : taskDetailsIds) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String s : idToArea.keySet()) {
                JSONArray objects = idToArea.get(s);
                for (Object o : objects) {
                    if (o.toString().contains(taskDetailsId.toString())) {
                        stringBuilder.append(" "+ s +" ");
                    }
                }
            }
            collect.put(taskDetailsId, stringBuilder.toString());
        }

        return collect;
    }

    private Map<Integer, String> getControl(Integer controlId) {
        List<SControlDetailVO> displayInterfaceDetailVOS = mapper.getControl(controlId);
        List<String> ids = new ArrayList<>();
        for (SControlDetailVO sControlDetailVO : displayInterfaceDetailVOS) {
            String taskDetailIds = sControlDetailVO.getTaskDetailIds();
            String[] split = taskDetailIds.split(",");
            for (String s : split) {
                ids.add(s);
            }
        }
        Map<Integer, String> respMap = new HashMap<>();
        for (String id : ids) {
            String a = "";
            StringBuilder stringBuilder = new StringBuilder();
            for (SControlDetailVO sControlDetailVO : displayInterfaceDetailVOS) {
                if (sControlDetailVO.getTaskDetailIds().contains(id)) {
                    a = a + sControlDetailVO.getEquipmentName() + " ";
                    //stringBuilder.append(sControlDetailVO.getBoby() +" ");
                }

            }
            respMap.put(Integer.parseInt(id), a);
        }

        return respMap;
    }


    public Object moduleById(Integer taskId, Integer displayId) {
        Map<Integer, String> displayArea = getDisplayArea(displayId);
        List<STaskFlowDetailVO> taskList = mapper.moduleById(taskId);
        List<SDisplayInterfaceDetailVO> S = mapper.getDisPlayName(displayId);
        SDisplayInterfaceVO sDisplayInterfaceVO = sDisplayInterfaceService.baseGetVOById(displayId);
        Map<Integer, String> collect = new HashMap<>();
        for (SDisplayInterfaceDetailVO sDisplayInterfaceDetailVO : S) {
            collect.put(sDisplayInterfaceDetailVO.getTaskFlowDetailId(), sDisplayInterfaceDetailVO.getInterestArea());
        }
        //Map<Integer, String> collect = S.stream().collect(Collectors.toMap(SDisplayInterfaceDetailVO::getTaskFlowDetailId, SDisplayInterfaceDetailVO::getInterestArea));
        List<moudle_1> respList = new ArrayList<>();
        for (STaskFlowDetailVO sTaskFlowDetailVO : taskList) {
            System.out.println(sTaskFlowDetailVO);
            moudle_1 moudle1 = new moudle_1();
            moudle1.setId(sTaskFlowDetailVO.getId());
            moudle1.setName(sTaskFlowDetailVO.getNodeName());
            //String name = JSONUtil.parseObj(collect.get(sTaskFlowDetailVO.getId())).getStr("name");
            if(displayId != 0){
                moudle1.setInterfaceName(displayArea.get(sTaskFlowDetailVO.getId()));
                moudle1.setDisplayName(sDisplayInterfaceVO.getDisplayName());
            }

            respList.add(moudle1);
        }

        return respList;
    }

    public Object moudleTaskNet(Integer id, Integer disPlayId, Integer controlId) {
        //根据任务ID 找到 对应的界面ID
        List<STaskFlowDetailEntity> list = mapper.getByTaskFlowId(id);
        Map<Integer, String> displayArea = null;
        Map<Integer, String> control = null;
        displayArea = getDisplayArea(disPlayId);
        control = getControl(controlId);
        List<TreeNode> nodeList = CollUtil.newArrayList();
        for (STaskFlowDetailEntity sTaskFlowDetailEntity : list) {
            TreeNode<String> stringTreeNode = new TreeNode<String>();
            stringTreeNode.setId(String.valueOf(sTaskFlowDetailEntity.getId()));

            stringTreeNode.setName(sTaskFlowDetailEntity.getNodeName());
            Map<String, Object> extra = new HashMap<>();
            extra.put("label", sTaskFlowDetailEntity.getNodeName());
            extra.put("type", sTaskFlowDetailEntity.getNodeName());
            extra.put("width", 100);
            extra.put("height", 40);
            extra.put("flowId", sTaskFlowDetailEntity.getId());

            if (displayArea.containsKey(sTaskFlowDetailEntity.getId())) {
                JSONObject entries = new JSONObject();
                entries.putOnce("label", displayArea.get(sTaskFlowDetailEntity.getId()));
                entries.putOnce("control", control.get(sTaskFlowDetailEntity.getId()));
                entries.putOnce("width", 100);
                entries.putOnce("height", 40);
                extra.put("category", entries);
            }

            String fId = sTaskFlowDetailEntity.getFId().replaceAll("\\[", "").replaceAll("]", "");
            System.out.println(fId);
            if (fId.contains(",")) {
                // 使用 Hutool 将字符串解析为 JSONArray
                JSONArray jsonArray = JSONUtil.parseArray(sTaskFlowDetailEntity.getFId());
                // 将 JSONArray 转换为 String[]
                String[] stringArray = jsonArray.toArray(new String[0]);
                extra.put("pointTo", stringArray);
                extra.put("pId", fId.split(",")[0]);
                stringTreeNode.setParentId(fId.split(",")[0]);
            } else {
                stringTreeNode.setParentId(sTaskFlowDetailEntity.getFId().replaceAll("\\[", "").replaceAll("]", ""));
            }
            stringTreeNode.setExtra(extra);
            nodeList.add(stringTreeNode);
        }

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都有默认值的
        treeNodeConfig.setWeightKey("order");
        treeNodeConfig.setIdKey("id");
        // 最大递归深度
        treeNodeConfig.setDeep(10);

        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<TreeNode, String>build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getId()));
                    tree.setParentId(String.valueOf(treeNode.getParentId()));
                    // 扩展属性 ...
                    tree.putExtra("label", treeNode.getExtra().get("label"));
                    tree.putExtra("width", treeNode.getExtra().get("width"));
                    tree.putExtra("height", treeNode.getExtra().get("height"));
                    tree.putExtra("flowId", treeNode.getExtra().get("flowId"));
                    tree.putExtra("flowId", treeNode.getExtra().get("flowId"));
                    tree.putExtra("pointTo", treeNode.getExtra().get("pointTo"));
                    tree.putExtra("category", treeNode.getExtra().get("category"));
                });
        return treeNodes;
    }

    public Object module2ById(Integer taskId, Integer disPlayId) {
        List<STaskFlowDetailVO> taskList = mapper.moduleById(taskId);
        List<SDisplayInterfaceDetailVO> S = mapper.getDisPlayName(disPlayId);
        SDisplayInterfaceVO sDisplayInterfaceVO = sDisplayInterfaceService.baseGetVOById(disPlayId);
        Map<Integer, String> collect = new HashMap<>();
        for (SDisplayInterfaceDetailVO sDisplayInterfaceDetailVO : S) {
            collect.put(sDisplayInterfaceDetailVO.getTaskFlowDetailId(), sDisplayInterfaceDetailVO.getInterestArea());
        }
        List<moudle_2> respList = new ArrayList<>();
        for (STaskFlowDetailVO sTaskFlowDetailVO : taskList) {
            System.out.println(sTaskFlowDetailVO);
            moudle_2 moudle2 = Convert.convert(moudle_2.class, sTaskFlowDetailVO);
            if(disPlayId != 0){
                moudle2.setDisplayName(sDisplayInterfaceVO.getDisplayName());
            }
            respList.add(moudle2);
        }
        return respList;
    }

    public Object module3ById(Integer taskId, Integer disPlayId) {
        List<STaskFlowDetailVO> taskList = mapper.moduleById(taskId);
        List<SDisplayInterfaceDetailVO> S = mapper.getDisPlayName(disPlayId);
        SDisplayInterfaceVO sDisplayInterfaceVO = sDisplayInterfaceService.baseGetVOById(disPlayId);
        Map<Integer, String> collect = new HashMap<>();
        for (SDisplayInterfaceDetailVO sDisplayInterfaceDetailVO : S) {
            collect.put(sDisplayInterfaceDetailVO.getTaskFlowDetailId(), sDisplayInterfaceDetailVO.getInterestArea());
        }
        List<moudle_3> respList = new ArrayList<>();
        for (STaskFlowDetailVO sTaskFlowDetailVO : taskList) {
            System.out.println(sTaskFlowDetailVO);
            moudle_3 moudle_3 = Convert.convert(moudle_3.class, sTaskFlowDetailVO);
            if(disPlayId != 0){
                //moudle_3.setDisplayName(sDisplayInterfaceVO.getDisplayName());
            }
            respList.add(moudle_3);
        }
        return respList;
    }


}
